<?php
declare (strict_types = 1);

namespace app\admin\middleware;
use think\facade\View;
use app\common\model\Admin;
use app\common\model\Config as ConfigModel;

class LoginAuth
{
     // 调用跳转扩展
     use \liliuwei\think\Jump;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取cookie
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? json_decode(cookie('LoginAdmin'),true) : [];

        if(empty($LoginAdmin))
        {
            $this->error('请先登录',(String)url('/admin/index/login'));
        }

        $Adminid = isset($LoginAdmin['id']) ? $LoginAdmin['id'] : 0;

        // 查询该用户是否存在数据库
        $Admin = Admin::find($Adminid);

        if(!$Admin)
        {
            cookie('LoginAdmin',null);
            $this->error('非法登录,请重新登录',(String)url('/admin/index/login'));
        }

        $data = [
            'id' => $Admin['id'],
            'username' => $Admin['username'],
            'nickname' => $Admin['nickname'],
            'state'=>$Admin['state']
        ];

        $ConfigList = ConfigModel::select();

        $Config = [];

        foreach ($ConfigList as $key => $value) {
           $Config[$value['key']] = $value['value'];
        }

        // 赋值给所有使用该中间件的视图
        View::assign([
            'LoginAdmin' => $data,
            'Config' => $Config
        ]);

        // 赋值给所有使用该中间件的控制器
        $request->LoginAdmin = $data;
        
        return $next($request);
    }
}
